import { Controller } from 'egg';
import puppeteer from 'puppeteer';
import path from 'path';
import {autoScroll} from '../utils';


export default class SavePdfController extends Controller {
  public async index() {
    const { ctx } = this;
   
    const { url } = ctx.request.body || {}
    // 启动浏览器
    const browser = await puppeteer.launch({
      headless: true, // 是否无头
      args: [ '--no-sandbox', '--font-render-hinting=medium' ],
    });
    const page = await browser.newPage();
    await page.goto(url, {
      // timeout: 60000,
      waitUntil: 'networkidle2', // networkidle2 会一直等待，直到页面加载后不存在 2 个以上的资源请求，这种状态持续至少 500 ms
    });
    console.log('ctx.header.host', ctx.header.host);
    
    const ext = '.pdf';
    const key = 'node_demo' + ext;
    const _path = path.resolve(`${__dirname}/../../`, key);
    await autoScroll(page);
    await page.pdf({ path: _path, format: 'a4' });
    await browser.close();
    
    ctx.response.body = {
      pdfUrl: `http://${ctx.header.host}/${key}`
    }
  }
}
